<template>
    <view class="order-list-main">
        <view class="head-nav">
            <view class="head-content" @click="checkIndex(index)" v-for="(item, index) in tablist" :key="index">
                <view :class="navIndex == index ? 'activite' : 'common'">{{ item.name }}</view>
                <view class="head_line" v-if="navIndex == index"></view>
            </view>
        </view>
        <view class="content">
            <view class="order-list" v-if="Data.isOrderList">
                <view
                    class="order-item"
                    v-for="(item, index) in Data.orderList"
                    :key="index"
                    @click="toOrderDetail(item)">
                    <view class="order-no">
                        <view v-if="navIndex == 5">订单号：{{ item.order && item.order[0]?.orderSn }}</view>
                        <view v-else>订单号：{{ item.orderSn }}</view>
                        <view class="order-no-s" v-if="navIndex == 5">
                            {{ item.refundStatusInfo?.refundStatusName }}
                        </view>
                        <view class="order-no-s" v-else>
                            {{ translateOrderCode(item.orderStatus, item.isSelfPickup) || item.orderStatusName }}
                        </view>
                    </view>
                    <view class="goods-info">
                        <template v-if="navIndex == 5">
                            <view class="goods-info-card" v-for="(ele, index) in item.refundGoods" :key="`k${index}`">
                                <GoodsCard
                                    v-for="e in ele.goods"
                                    :key="e.id"
                                    :orderType="item.order[0]?.orderType || 1"
                                    :goodsData="e" />
                            </view>
                        </template>
                        <view class="goods-info-card" v-for="(ele, index) in item.goods" :key="`k${index}`">
                            <GoodsCard :orderType="item.orderType" :goodsData="ele" />
                        </view>

                        <view class="goods-info-other" v-if="navIndex == 5">
                            共{{ getBuyNum(item.refundGoods, '2') }}件商品 <text class="total">合计</text>
                            <!-- <text class="price">￥{{ getRefundAmount(item.refundGoods) }}</text> -->
                            <text class="price">￥{{ floatDivide(item.refundPaymentFee, 100) }}</text>
                        </view>
                        <view class="goods-info-other" v-else>
                            共{{ getBuyNum(item.goods) }}件商品 <text class="total">合计</text>
                            <text class="price">￥{{ floatDivide(item.orderAmountTotal, 100) }}</text>
                        </view>
                    </view>
                    <view class="order-button-goto" v-if="item.spellOrderId && item.orderStatus === 6">
                        <view class="order-button-group">
                            <view @click.stop="gotoGrow(item.spellOrderId)">查看拼团详情</view>
                        </view>
                    </view>
                    <view
                        class="order-button"
                        :class="{ 'order-button-end': item.orderStatus != 1 }"
                        v-if="item.orderStatus == 1">
                        <view class="order-button-left">
                            <view
                                class="order-button-left"
                                v-if="item.orderStatus == 1 && checkCountdow(item.createdAt, item.autoCancelMinutes)">
                                交易关闭剩余：<CountDown
                                    :endTime="getTimeStamp(item.createdAt, 60000 * item.autoCancelMinutes)" />
                            </view>
                        </view>
                        <view class="order-button-right">
                            <view
                                v-if="item.orderStatus == 1"
                                class="order-button-item"
                                @click.stop="cancelOrder(item)">
                                取消订单
                            </view>
                            <view
                                v-if="item.orderStatus == 1"
                                class="order-button-item order-button-item-color"
                                @click.stop="toPay(item)">
                                付款
                            </view>
                        </view>
                    </view>
                </view>
                <view class="list-loading">
                    {{ listLoading && isBottom ? '加载中…' : isBottom ? '已经到底啦！' : '' }}
                </view>
            </view>
            <view class="no-list" v-else>
                <image class="no-list-img" :src="getImgOssUrl('/ui-prod-2.0.0/order_img_2.0.png')" />
                <view class="no-list-text">您还没有相关订单</view>
            </view>
            <!-- 取消弹框 -->
            <view class="popup-dialog" v-if="Dialog.cancelShow" :catchtouchmove="true">
                <view class="popup-dialog-content">
                    <view class="title">您确定要取消订单吗，取消后无法恢复</view>
                    <view class="button">
                        <view class="cancel" @click="Dialog.cancelShow = false">取消</view>
                        <view class="confirm" @click="cancelOrderConfirm">确认</view>
                    </view>
                </view>
            </view>
            <!-- 库存不足取消订单 -->
            <MessageBox
                ref="messagebox"
                :content="Dialog.content"
                btnName="取消订单"
                @comfirm="cancelOrderConfirm"></MessageBox>
        </view>
        <Loading />
    </view>
</template>
<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { onShow, onPullDownRefresh, onReachBottom, onPageScroll } from '@dcloudio/uni-app';
import { floatDivide, getTimeStamp, checkCountdow, getImgOssUrl, translateOrderCode } from '@/commons/utils.js';
import request from '@/request';
import router from '@/router';
import GoodsCard from '@/components/goodsCard';
import CountDown from '@/components/countdown';
import MessageBox from '@/components/messageBox';
import Loading from '@/components/el-loading';
import { useTrace } from '@/commons/trace';
import subscribe from '@/commons/subscribe';
import { debounce } from 'lodash';

const messagebox = ref();

const { traceReport } = useTrace();

const props = defineProps({
    status: {
        type: [String, Number],
        default: 0
    }
});

const listLoading = ref(true);

const navIndex = ref(props.status);

const tablist = [
    { name: '全部', code: 0 },
    { name: '待付款', code: '1' },
    { name: '待发货', code: '2' },
    { name: '待收货', code: '3' },
    { name: '交易完成', code: '4' },
    { name: '售后', code: '5' }
];

const queryInfo = reactive({
    page: 1,
    perPage: 10,
    shopId: uni.getStorageSync('ZW_SHOP_ID'),
    buyerUid: '',
    orderStatus: props.status,
    source: 'mini'
});

const Data = reactive({
    isOrderList: true,
    orderList: [],
    totalCount: 0,
    orderId: '',
    orderSn: '',
    orderType: '',
    orderAmountTotal: '',
    scrollTop: 0
});

const Dialog = reactive({
    cancelShow: false,
    content: '',
    info: {}
});

const isBottom = computed(() => {
    return Data.scrollTop > 100;
});

onPullDownRefresh(() => {
    queryInfo.page = 1;
    if (navIndex.value == 5) {
        getRefundOrderList();
    } else {
        getOrderList();
    }
});

onReachBottom(() => {
    if (Data.totalCount == Data.orderList.length) {
        return;
    }
    queryInfo.page++;
    if (navIndex.value == 5) {
        getRefundOrderList(true);
    } else {
        getOrderList(true);
    }
});

const getOrderList = async type => {
    listLoading.value = true;
    let params = { ...queryInfo };
    let res = await request('orderMineServ', params);
    let list = res.data.list || [];
    list.forEach(x => {
        x.goods.forEach(e => {
            e.goodsNum = e.buyNum;
            e.specValueList = e.skuExtInfo;
            e.goodsPrice = x.orderType === 6 && e.goodsType === 1 ? e.sellPrice : e.goodsPrice;
            e.goodPoints = x.orderType === 6 ? e.goodPoints : '';
        });
    });
    if (type) {
        Data.orderList = Data.orderList.concat(list);
    } else {
        Data.orderList = list;
    }
    Data.totalCount = res.data.totalCount;
    if (!list.length) {
        Data.isOrderList = false;
    }
    if (Data.orderList.length == Data.totalCount) {
        listLoading.value = false;
    }
    uni.stopPullDownRefresh();
};

const getRefundOrderList = async type => {
    listLoading.value = true;
    let params = {
        page: queryInfo.page,
        perPage: queryInfo.perPage
    };
    let res = await request('refundOrderListServ', params);
    let list = res.data.list || [];
    list.forEach(x => {
        x.refundGoods.forEach(e => {
            e.goods.forEach(i => {
                i.goodsNum = e.refundGoodsCount;
                i.specValueList = i.skuExtInfo;
                i.goodsPrice = x.order[0].orderType === 6 ? i.sellPrice : i.goodsPrice;
                i.goodPoints = x.order[0].orderType === 6 ? i.goodPoints : '';
            });
        });
    });
    if (type) {
        Data.orderList = Data.orderList.concat(list);
    } else {
        Data.orderList = list;
    }
    Data.totalCount = res.data.totalCount || 0;
    if (!list.length) {
        Data.isOrderList = false;
    }
    if (Data.orderList.length == Data.totalCount) {
        listLoading.value = false;
    }
    uni.stopPullDownRefresh();
};

const checkIndex = index => {
    navIndex.value = index;
    queryInfo.page = 1;
    queryInfo.orderStatus = tablist[index].code;
    Data.isOrderList = true;
    if (index == 5) {
        getRefundOrderList();
    } else {
        getOrderList();
    }
    uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
    });
};
checkIndex(navIndex.value);

const getBuyNum = (list, type) => {
    if (!list) return;
    if (type == '2') {
        return list.reduce((pre, cur) => pre + cur.refundGoodsCount, 0);
    } else {
        return list.reduce((pre, cur) => pre + cur.buyNum, 0);
    }
};

const getRefundNum = (list, type) => {
    if (!list) return;
    if (type == '2') {
        return list.reduce((pre, cur) => pre + cur.refundGoodsCount, 0);
    } else {
        return list.reduce((pre, cur) => pre + cur.buyNum, 0);
    }
};

const getBuyAmount = (list, logisticsFee) => {
    if (!list) return;
    let total = list.reduce((pre, cur) => pre + cur.total, 0);
    return floatDivide(total + logisticsFee, 100);
};

const getRefundAmount = list => {
    if (!list) return;
    let total = list.reduce((pre, cur) => pre + cur.goods[0]?.total, 0);
    return floatDivide(total, 100);
};

const cancelOrder = val => {
    Dialog.cancelShow = true;
    Dialog.info = val;
};

const gotoGrow = val => {
    router.push('/pages-cart/group/index?spellOrderId=' + val);
};

const cancelOrderConfirm = async () => {
    /*************埋点代码开始***********************/
    const traceGoodsList = [];
    Dialog.info?.goods?.map(item => {
        traceGoodsList.push({
            productId: item.goodsId,
            productName: item.goodsName,
            skuId: item.skuId
        });
    });
    traceReport('cancel_order', {
        orderId: Dialog.info?.id,
        goods: traceGoodsList
    });
    /*************埋点代码结束***********************/
    let params = {
        shopId: queryInfo.shopId,
        orderId: Dialog.info?.id
    };
    let res = await request('orderCancelServ', params);
    if (res.data) {
        Dialog.cancelShow = false;
        messagebox?.value?.closePopup();
        queryInfo.page = 1;
        getOrderList();
        uni.showToast({
            title: '取消成功',
            icon: 'none'
        });
    }
};

// 进店逛逛
const toHome = () => {
    router.switchTab({ url: '/pages/tabbar/home' });
};

// 重新参与
const toGoodsDetail = item => {
    router.push({
        path: '/pages-cart/good/index',
        query: {
            activityId: item.activityId,
            goodsId: item.goods[0].goodsId
        }
    });
};

const toPay = debounce(async val => {
    // 获取操作的订单
    Dialog.info = val;
    if ([3, 4, 5].includes(val.orderType) && val.spellOrderId) {
        try {
            await request('getOffereCheckGroupServ', { spellOrderId: val.spellOrderId });
            toPayHadCheck(val);
        } catch (error) {
            // 4000003 该团已失效，请重新选择,4000004 活动已结束，下次早点来哦 4000005 该团已满，请重新选择,4000006 仅新用户可参团，你不符合参团
            switch (error.data.code) {
                case 4000003:
                    uni.showModal({
                        content: error.data.msg,
                        cancelText: '我知道了',
                        confirmText: '重新参与',
                        confirmColor: '#FF4D4F',
                        success: e => {
                            if (e.confirm) {
                                toGoodsDetail(val);
                            }
                        }
                    });
                    break;
                case 4000004:
                    uni.showModal({
                        content: error.data.msg,
                        confirmText: '进店逛逛',
                        cancelText: '我知道了',
                        confirmColor: '#FF4D4F',
                        success: e => {
                            if (e.confirm) {
                                toHome();
                            }
                        }
                    });
                    break;
                case 4000005:
                    uni.showModal({
                        content: error.data.msg,
                        confirmText: '进店逛逛',
                        cancelText: '我知道了',
                        confirmColor: '#FF4D4F',
                        success: e => {
                            if (e.confirm) {
                                toHome();
                            }
                        }
                    });
                    break;
                default:
                    uni.showModal({
                        content: error.data.msg,
                        confirmText: '我知道了',
                        showCancel: false,
                        confirmColor: '#FF4D4F',
                        success: () => {}
                    });
                    break;
            }
        }
    } else {
        toPayHadCheck(val);
    }
}, 800);

const toPayHadCheck = val => {
    Data.orderId = val.id;
    Data.orderSn = val.orderSn;
    Data.orderType = val.orderType;
    Data.orderAmountTotal = val.orderAmountTotal;
    payChannelList();
    /*******************埋点代码开始************************/
    traceReport('pay_order', {
        orderId: Data.orderId,
        payAccount: Data.orderAmountTotal
    });
    /*******************埋点代码结束************************/
};

const payChannelList = async () => {
    await subscribe('order_payment');
    let res = await request('payChannelListServ');
    let payChannel = res.data.payList?.[0];
    wxPay(payChannel);
};

const wxPay = async val => {
    let params = {
        orderSn: Data.orderSn,
        payMethod: val.type
    };
    try {
        let res = await request('payPrepayServ', params);
        let obj = res.data || {};
        // isPaymentApp=true: 商户绑定了支付小程序且开通了宝付支付
        if (res.data?.isPaymentApp) {
            router.push(
                `/pages-cart/cashier/index?appId=${obj.appId}&amount=${Data.orderAmountTotal}&orderSn=${Data.orderSn}&payMethod=${val.type}&orderId=${Data.orderId}&orderType=${Data.orderType}&type=3`
            );
        } else {
            uni.requestPayment({
                provider: 'wxpay',
                timeStamp: obj.timeStamp,
                nonceStr: obj.nonceStr,
                package: obj.package,
                signType: obj.signType,
                paySign: obj.paySign,
                success: function (res) {
                    router.redirectTo({
                        url: `/pages-cart/paystatus/index?orderId=${Data.orderId}&orderType=${Data.orderType}`
                    });
                },
                fail: function (err) {
                    request('payCancelServ', { orderSn: Data.orderSn, payMethod: val.type });
                    router.push({
                        path: '/pages-user/orderdetail/index',
                        query: {
                            orderId: Data.orderId
                        }
                    });
                }
            });
        }
    } catch (err) {
        if ([9002110, 9002109].includes(err.data?.code)) {
            Dialog.content = err.data?.msg;
            messagebox.value.openPopup();
        } else {
            uni.showToast({
                title: err.data?.msg || '网络错误，请稍后重试~',
                icon: 'none',
                duration: 2000
            });
        }
    }
};

const toOrderDetail = val => {
    if (navIndex.value == 5) {
        if (val.refundStatus == 2) {
            // refundgoods
            router.push({
                path: '/pages-user/refundgoods/index',
                query: {
                    orderId: val.orderId,
                    refundOrderId: val.id
                }
            });
        } else {
            router.push({
                path: '/pages-user/refunddetail/index',
                query: {
                    orderId: val.id
                }
            });
        }
    } else {
        router.push({
            path: '/pages-user/orderdetail/index',
            query: {
                orderId: val.id
            }
        });
    }
};

const isRefundBtn = code => {
    return [2, 3, 4].includes(code) && navIndex.value != 5;
};

onPageScroll(e => {
    Data.scrollTop = e.scrollTop;
});

onShow(() => {});
</script>
<style lang="scss" src="./index.scss" scoped></style>
